<html>
<head>
    <meta charset="UTF-8">
    <title>Web sockets test</title>
</head>
<body>

<input id="name" value="" placeholder="用户名">
<button id="login" type="button" onclick="login()" value="">登陆</button>
<br/><br/>
<input id="onename" value="" placeholder="发给谁">
<br/><br/>
<input id="data">
<button type="button" onclick='SendData();'>发送消息</button>
<br/><br/>
<div id="info">
</div>

</body>

<script type="text/javascript">
    var ws;
    function login() {
        if (!ws) {
            // var user = document.getElementById("name").value;
            // var uuid = document.getElementById("onename").value;
            var user = 'wsw';
            var uuid = 'xpq';
            console.log("uuid:" + uuid);
            try {
                //注意端口是否一致
                ws = new WebSocket("ws://127.0.0.1:8081/onewebsocket/" + user + "/" + uuid);//连接服务器
                ws.onopen = function (event) {
                    console.log("已经与服务器建立了连接...");
                    alert("登陆成功，可以开始聊天了")
                };
                ws.onmessage = function (event) {
                    console.log("接收到服务器发送的数据..." + event.data);
                    document.getElementById("info").innerHTML += event.data + "<br>";
                };
                ws.onclose = function (event) {
                    console.log("已经与服务器断开连接...");
                };
                ws.onerror = function (event) {
                    console.log("WebSocket异常！");
                };
            } catch (ex) {
                alert(ex.message);
            }
            document.getElementById("login").innerHTML = "退出";
        } else {
            ws.close();
            ws = null;
        }
    }

    //发送信息
    function SendData() {
        var data = document.getElementById("data").value;
        try {
            ws.send(data);
        } catch (ex) {
            alert(ex.message);
        }
    };

</script>


</html>
